<?php
/**
 * Created by PhpStorm.
 * User: yiyu
 * Email: smalleasyu@gmail.com
 * Date: 2020-01-18 22:19:44
 * Desc:
 */

namespace app\api\service;

use app\base\service\BaseService;
use app\base\model\user\{User, UserAccountLog, UserAccount};
use app\base\model\system\SystemConfig;
use app\core\exception\BusinessException;
use app\core\exception\ErrorCode;
use app\core\log\Log4dd;

class UserRegisterService extends BaseService
{

    public static function miniProgramUserRegister($data)
    {

        Log4dd::info('小程序注册参数', func_get_args());
        try {

            $refer_user_id = 0;

            if (isset($data['refer_code']) && $data['refer_code']) {
                $refer_user_id = User::getUserIdByReferCode($data['refer_code']);
            }

            $register_data = [
                'nick_name' => $data['nickName'] ?? '',
                'gender' => $data['gender'] ?? 0,
                'big_avatar_url' => $data['avatarUrl'] ?? '',
                'small_avatar_url' => $data['avatarUrl'] ?? '',
                'country' => $data['country'] ?? '',
                'province' => $data['province'] ?? '',
                'city' => $data['city'] ?? '',
                'refer_user_id' => $refer_user_id
            ];

            $new_user = User::miniProgramRegisterNewUser($register_data);

            if ($new_user == false) {
                throw new BusinessException(ErrorCode::COMMON_ERROR, '小程序注册用户失败1');
            }

            if (!isset($new_user['user_id'])) {
                throw new BusinessException(ErrorCode::COMMON_ERROR, '小程序注册用户失败2');
            }

            return $new_user['user_id'];

        } catch (BusinessException $e) {
            Log4dd::info("小程序注册用户失败:{$e->getMessage()}", func_get_args(), $e);
            throw new BusinessException(ErrorCode::COMMON_ERROR, $e->getMessage());
        }


    }

    public static function mobileUserRegister()
    {

    }

    public static function RegisterGiveWishCoin($user_id)
    {
        //判断是否领取过
        $give_info = UserAccountLog::hasAlreadyReceivedRegisterReward($user_id);

        if ($give_info) {
            throw new BusinessException(ErrorCode::COMMON_SUCCESS, '已经领取过');
        }

        $register_give_wish_coin_num = SystemConfig::getNewUserGiveWishCoinNum();

        $res = UserAccount::operationUserAccount($user_id, $user_id, UserAccount::WISH_COIN,
            $register_give_wish_coin_num, 'register_give', '领取新人福利二重礼礼包');

        if ($res && isset($res['err_num']) && $res['err_num'] == 0) {
            return $register_give_wish_coin_num;
        } else {
            throw new BusinessException(ErrorCode::COMMON_SUCCESS, '领取失败');
        }
    }


}